const express = require("express");
const router = express.Router();

// 导入生成token的包
const jwt = require("jsonwebtoken");
// 导入全局的配置文件，密文
const config = require("../config");

let { conMysql } = require("../db");

//实现登录流程

router.post("/login", (req, res) => {
    //获取客户端传递过来的用户名和密码
    let { username, password } = req.body;

    //判断用户名密码是否为空
    if (!username || !password) {
        res.output("用户名或密码不能为空", 1001, null);
        return;
    }

    const sql = `select * from db_user where username='${username}' and password='${password}'`;
    conMysql(sql)
        .then((result) => {
            console.log(result);

            //判断是否登录成功
            if (result.length == 0) {
                res.output("用户名或密码错误", 1001, null);
                return;
            }
            const user = { ...result[0], password: "" };
            //生成token
            const tokenStr = jwt.sign(user, config.jwtSecretKey, {
                expiresIn: config.expiresIn,
            });
            res.output("登录成功", 0, { username, token: `Bearer ${tokenStr}` });
        })
        .catch((err) => {
            console.log(err);
            res.output(err, 500, null);
        });
});

module.exports = router;
